package com.fuershiye.woman.monitor.controller;

import com.fuershiye.woman.monitor.beans.DepartmentAndType;
import com.fuershiye.woman.monitor.beans.IdName;
import com.fuershiye.woman.monitor.beans.Result;
import com.fuershiye.woman.monitor.constants.CodeName;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.constants.PermissionEnum;
import com.fuershiye.woman.monitor.constants.Roles;
import com.fuershiye.woman.monitor.model.*;
import com.fuershiye.woman.monitor.service.AreaService;
import com.fuershiye.woman.monitor.service.UserService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 传统区域的管理
 *
 * @author yongyongdong
 *
 */
@Controller
@RequestMapping(value = "/area/query")
@SuppressWarnings("unchecked")
public class AreaQueryController {

	private static final Logger logger = LoggerFactory
			.getLogger(AreaQueryController.class);

	@Autowired
	AreaService areaService;
	@Autowired
	UserService userService;

	//	@RequiresPermissions("area:samePid")
	@RequestMapping(value = "/self.do")
	@ResponseBody
	public Result self() {

        User user = userService.getDByName(SecurityUtils.getSubject().getPrincipal() + "");
		if(user==null){
			return new Result(Massage.USER_IS_NULL);
		}
        List<Role> roles = user.getRoles();
        String userArea = "";
        for (Role role : roles) {
            if(role==null){
                continue;
            }
            if(role.getPermissions().size()<1){
                continue;
            }
            for (Permission permission : role.getPermissions()) {
                if(permission==null){
                    continue;
                }
                if(permission.getPermissionCode()==null){
                    continue;
                }

                //用户三种角色只能所属一种。
                //省级别的人员，可查看所有地级市  -查看全省（各地市）
                if(permission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_PROVINCE.getValue())){
                    userArea = permission.getPermissionCode();
                    break;
                }
                //地市级别的人员，可查看本市所有区县事
                if(permission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_CITY.getValue())){
                    userArea = permission.getPermissionCode();
                    break;
                }
                //区县级别的人员，可查看本区县数据的上报情况
                if(permission.getPermissionCode().equals(PermissionEnum.PERMISSION_AREALIST_COUNTY.getValue())){
                    userArea = permission.getPermissionCode();
                    break;
                }
            }
        }

        Map result = Maps.newHashMap();

        //地域级别 1：国家;2:省，直辖市;3:地级;4:区县;5:乡镇级;6:其他
        int level3 = 3;
        int level4 = 4;

        //省级别的人员，可查看所有地级市  -查看全省（各地市）
        if(userArea.equals(PermissionEnum.PERMISSION_AREALIST_PROVINCE.getValue())){

            Map mapProvince = Maps.newHashMap();
            mapProvince.put("level",CodeName.PROVINCE);
            mapProvince.put("id",null);
            mapProvince.put("name","");
            Area area = areaService.findByCode(CodeName.PROVINCE);
            if(area!=null){
                mapProvince.put("id",area.getId());
                mapProvince.put("name",area.getName());
            }

            List<Map> provincelist = Lists.newArrayList();
            List<IdName> provinceList = areaService.getIdNameByLevelAndPid(level3, null);
            for (IdName idName : provinceList) {
                if(idName==null){
                    continue;
                }
                Map mapCity = Maps.newHashMap();
                mapCity.put("level",CodeName.CITY);
                mapCity.put("id",idName.getId());
                mapCity.put("name",idName.getName());

                List<IdName> cityList = areaService.getIdNameByLevelAndPid(level4, idName.getId());
                mapCity.put("list",cityList);
                if(cityList.size()>1){
                    provincelist.add(mapCity);
                }
            }
            mapProvince.put("list",provincelist);
            result =mapProvince;
        }

        //地市级别的人员，可查看本市所有区县
        if(userArea.equals(PermissionEnum.PERMISSION_AREALIST_CITY.getValue())){

            Department department = userService.getDepartIdByName(SecurityUtils.getSubject().getPrincipal() + "");
            if(department==null||department.getArea()==null||department.getArea()<1){
                return new Result(Massage.DEPART_IS_NULL);
            }

            Area area = areaService.get(department.getArea());
            if(area==null){
                return new Result(Massage.AREA_IS_NULL);
            }

            Map mapCity = Maps.newHashMap();
            mapCity.put("level",CodeName.CITY);
            mapCity.put("id",area.getId());
            mapCity.put("name",area.getName());

            List<IdName> cityList = areaService.getIdNameByLevelAndPid(level4, area.getId());
            mapCity.put("list",cityList);
            result =mapCity;
        }

        //区县级别的人员，可查看本区县数据的上报情况
        if(userArea.equals(PermissionEnum.PERMISSION_AREALIST_COUNTY.getValue())){
            Area area = userService.getAreaByName();
            if(area==null){
                return new Result(Massage.AREA_IS_NULL);
            }
            result.put("level",CodeName.COUNTY);
            result.put("id",area.getId());
            result.put("name",area.getName());
            result.put("list",null);
        }

		return new Result(Massage.SUCCESS, result);
	}


    //query
    //	@RequiresPermissions("area:samePid")
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/selfCity.do")
    @ResponseBody
    public Result querySelfCity() {

        //地域级别 1：国家;2:省，直辖市;3:地级;4:区县;5:乡镇级;6:其他
        int level = 3;

        DepartmentAndType departmentAndType = userService.getDepartTypeByName();
        if(departmentAndType==null){
            return new Result(Massage.DEPART_IS_NULL);
        }

        if(departmentAndType.getTcode().equals(CodeName.DEPART_TYPE_ADMIN)){
            return new Result(Massage.SUCCESS, areaService.getIdNameByLevelAndPid(level, null));
        }

        List<IdName> result = Lists.newArrayList();
        String userRole = "";
        //区县管理员
        if(userRole.equals(Roles.ROLE_CODE_ADMIN_COUNTY.getValue())){
            Area area = userService.getAreaByName();
            if(area==null){
                return new Result(Massage.AREA_IS_NULL);
            }
            IdName idName = new IdName();
            idName.setId(area.getId());
            idName.setName(area.getName());
            result.add(idName);
        }

        if(departmentAndType.getTcode().equals(CodeName.DEPART_TYPE_TONGJI)){

            //其他部门类型的用户，只能看到自己当前地区
            Area area = userService.getAreaByName();
            if(area==null){
                return new Result(Massage.AREA_IS_NULL);
            }

            IdName idName = new IdName();
            idName.setId(area.getId());
            idName.setName(area.getName());
            result.add(idName);

            return new Result(Massage.SUCCESS, result);
        }
        return new Result(Massage.SUCCESS, result);
    }

    //query
    //areaid 省级地域的ID
    // 比如：areaid是德州地区的地域ID，返回的是：平原县，临邑县，夏津县等
    //	@RequiresPermissions("area:samePid")
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/county.do")
    @ResponseBody
    public Result getCounty(Long areaid) {

        if(areaid==null||areaid==0){
            return new Result(Massage.ERROR_PARAMETER );
        }

        //地域级别 1：国家;2:省，直辖市;3:地级;4:区县;5:乡镇级;6:其他
        Integer level = 4;

        return new Result(Massage.SUCCESS, areaService.getIdNameByLevelAndPid(level, areaid));
    }

}
